package com.bestcem.xm.user.util.business;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.user.constant.UserCacheKeyConstant;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 用户上传锁工具类
 *
 * @author Linzhijian <zhijian.lin@idiaoyan.com>
 * @version v1.0
 * @date 2022/08/05 10:55
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Component
@Slf4j
public class UserLockUtil {

    @Autowired
    private RedisService redisService;

    /**
     * 账号上传锁
     *
     * @param orgId
     * @return java.lang.Boolean true：锁定成功、false：锁定失败
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/08/05 10:56
     */
    public Boolean lock(String orgId) {
        String lockKey = String.format(UserCacheKeyConstant.USER_UPLOAD_LOCK_KEY, orgId);
        return redisService.setIfAbsent(lockKey, String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 删除账号上传锁
     *
     * @param orgId 租户id
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/08/05 10:56
     */
    public void unlock(String orgId) {
        String lockKey = String.format(UserCacheKeyConstant.USER_UPLOAD_LOCK_KEY, orgId);
        redisService.del(lockKey);
    }

    /**
     * 判断当前租户的账号上传的锁定状态
     *
     * @param orgId 租户id
     * @return boolean true：已被锁定、false：未被锁定
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/08/05 10:56
     */
    public boolean getLockFlag(String orgId) {
        if (!ObjectId.isValid(orgId)) {
            return true;
        }
        String lockKey = String.format(UserCacheKeyConstant.USER_UPLOAD_LOCK_KEY, orgId);
        Boolean bool = redisService.hasKey(lockKey);
        return null != bool && bool;
    }


}
